package com.lange.autocode.customDict;

import cn.net.autocode.core.bean.ResultT;
import cn.net.autocode.core.utils.TreeUtils;
import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.platform.customDict.CustomDict;
import cn.net.autocode.platform.customDict.CustomDictAnnotation;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Component;

@Component
@CustomDictAnnotation("region")
public class RegionDict implements CustomDict {

    private final Dao dao;

    public RegionDict(Dao dao) {
        this.dao = dao;
    }

    @Override
    public ResultT query(JSONObject param) {
        String sql = "select t.parent_id,t.id,t.code value,t.name label from sys_region t where level_id<=? order by code";
        JSONArray array = dao.queryJSONArray(sql,3);
        JSONArray treeArray = TreeUtils.commonTree(array);
        treeArray = this.filter("100000",treeArray);
        return ResultT.success(treeArray);
    }

    private JSONArray filter(String code, JSONArray treeArray){
        int size = treeArray.size();
        for(int i=0;i<size;i++){
            JSONObject json = treeArray.getJSONObject(i);
            if(code.equals(json.getString("value"))){
                return json.getJSONArray("children");
            }
        }
        return new JSONArray();
    }
}
